import prisma from '@/lib/prisma';
import { Prisma } from '@prisma/client';

export class PeriodService {
  static async getPeriods(userId: string, year?: number, month?: number) {
    try {
      let whereClause: Prisma.PeriodWhereInput = {
        user_id: userId,
      };

      if (year && month) {
        const startDate = new Date(year, month - 1, 1);
        const endDate = new Date(year, month, 0);
        whereClause.start_date = {
          gte: startDate,
          lte: endDate,
        };
      }

      const periods = await prisma.period.findMany({
        where: whereClause,
        orderBy: {
          start_date: 'desc',
        },
      });

      return periods;
    } catch (error) {
      console.error('PeriodService getPeriods error:', error);
      throw error;
    }
  }

  static async createPeriod(data: { user_id: string; start_date: Date }) {
    try {
      return await prisma.period.create({
        data: {
          user_id: data.user_id,
          start_date: data.start_date,
        },
      });
    } catch (error) {
      console.error('PeriodService createPeriod error:', error);
      throw error;
    }
  }

  static async updatePeriod(id: string, data: { end_date?: Date }) {
    try {
      let duration: number | null = null;
      
      if (data.end_date) {
        const period = await prisma.period.findUnique({ where: { id } });
        if (period) {
          const start = new Date(period.start_date);
          const end = new Date(data.end_date);
          duration = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
        }
      }

      return await prisma.period.update({
        where: { id },
        data: {
          ...data,
          duration,
        },
      });
    } catch (error) {
      console.error('PeriodService updatePeriod error:', error);
      throw error;
    }
  }

  static async deletePeriod(id: string) {
    try {
      await prisma.period.delete({
        where: { id },
      });
      return true;
    } catch (error) {
      console.error('PeriodService deletePeriod error:', error);
      throw error;
    }
  }
} 